//
//  PictureSelectorController.swift
//  PicturePicker(照片选择)
//
//  Created by 焦林生 on 15/11/17.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit

//可重用标示符
private let PictureSelectorCellID  = "PictureSelectorCellID"

//最大照片数量
private let PictureSelectorMaxPictureCount = 9

class PictureSelectorController: UICollectionViewController {
    
    //照片数组
    lazy var pictures = [UIImage]()
    
    //当前选中照片的索引
    private var currentIndex = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

      //注册可重用cell
        self.collectionView!.registerClass(pictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellID)
    }
    
    //MARK: 构造函数
    init() {
    
        super.init(collectionViewLayout: pictureSelectorLayout())
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 照片选择器布局(类中类)
    private class pictureSelectorLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            //ios9以后 不建议过分依赖UIScreen
            let count: CGFloat = 4
            //6s 2   6s+ 3
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        }
    }
   
    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return pictures.count + (pictures.count < PictureSelectorMaxPictureCount ? 1 : 0)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellID, forIndexPath: indexPath) as! pictureSelectorCell

        //设置图像
        cell.image = (indexPath.item == pictures.count) ? nil : pictures[indexPath.item]
        
        cell.pictureDelegate = self
        return cell
    }

}
// MARK: - PictureSelectorCellDelegate
extension PictureSelectorController: pictureSelectorCellDelegate{

    //添加照片
    @objc private func pictureSelectorCellDidAdd(cell: pictureSelectorCell) {
    
        //判断是否支持照片选择
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
        
            print("无法访问照片")
            return
        }
        //访问相册
        let picker = UIImagePickerController()
        
        //记录当前用户选中索引
        currentIndex = collectionView!.indexPathForCell(cell)!.item
        //设置代理
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    //删除照片
    @objc private func pictureSelectorCellDidRemove(cell: pictureSelectorCell) {
    
        //1 获取当前索引
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        //2 判断索引是否超出上限
        if indexPath.item >= pictures.count {
        
            return
        }
        //3 删除数据
        pictures.removeAtIndex(indexPath.item)
        
        //4 动画刷新视图(单纯的刷新数据 没有动画 不会检测到item)
        collectionView?.reloadData()
        
    }
}
// MARK: - UIImagePickerControllerDelegate,UINavigationControllerDelegate
extension PictureSelectorController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    /**
    选择照片代理方法
    
    - parameter picker: 照片选择器
    - parameter info:   信息字典
    */
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
         let scaleImage = image.scaleImage(600)
        
        if currentIndex < pictures.count {
        
            pictures[currentIndex] = scaleImage
        } else {
        
            //将图片添加到数组
            pictures.append(scaleImage)
        }
     
        //刷新数据
        collectionView?.reloadData()
        
        //释放控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//MARK: 定义协议(如果协议是私有的,那么协议方法也是私有的)
@objc private protocol pictureSelectorCellDelegate: NSObjectProtocol {

    //添加照片
    optional func pictureSelectorCellDidAdd(cell: pictureSelectorCell)
    
    //删除照片
    optional func pictureSelectorCellDidRemove(cell: pictureSelectorCell)
}

//MARK: 照片选择 cell
private class pictureSelectorCell:UICollectionViewCell {

    //照片选择代理
    weak var pictureDelegate: pictureSelectorCellDelegate?
    
    //照片
    private var image: UIImage? {
        
        didSet {
            
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            
            //默认隐藏删除按钮
            removeButton.hidden = (image == nil)
        }
    }
    
   //MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 监听方法
    //添加照片
    @objc private func addPicture() {
    
        print("添加照片")
        pictureDelegate?.pictureSelectorCellDidAdd?(self)
    }
    
    //删除照片
    @objc private func removePicture() {
    
        pictureDelegate?.pictureSelectorCellDidRemove?(self)
    }
    
    
    
    //MARK: 设置界面
    private func setupUI() {
    
        //1 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        
        //2 自动布局
        addButton.frame = bounds
//        addButton.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView.snp_edges)
//        }
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        //3 监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        //4 设置照片填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
        
    }
    
    //MARK: 懒加载控件
    //添加按钮
    private var addButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    //删除按钮
    private var removeButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}







